// pages/my/my.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 示例数据，实际需从后台获取
        assets: {
            储值: 100,
            积分: 500,
            优惠券: 3,
            权益卡: 1
        },
        currentOrderTab: 0, // 当前订单选项卡
        orderCounts: [2, 1, 3, 0, 12], // 各状态订单数量
        orders: [
          // 待付款订单
          [
            {
              id: 1001,
              orderNo: '202509230001',
              status: 0,
              statusText: '待付款',
              statusClass: 'pending',
              productImage: 'https://xxx.xjdio.com/static/img/1.jpg',
              productName: '手工奶皮子酸奶',
              specification: '蜜桃味',
              price: 9.00,
              quantity: 1,
              createTime: '2025-09-23 14:30:15'
            },
            {
              id: 1002,
              orderNo: '202509230002',
              status: 0,
              statusText: '待付款',
              statusClass: 'pending',
              productImage: 'https://xxx.xjdio.com/static/img/2.jpg',
              productName: '手工奶皮子酸奶',
              specification: '蜜桃味',
              price: 9.00,
              quantity: 2,
              createTime: '2025-09-23 13:22:05'
            }
          ],
          // 待发货订单
          [
            {
              id: 1003,
              orderNo: '202509220001',
              status: 1,
              statusText: '待发货',
              statusClass: 'pending',
              productImage: 'https://xxx.xjdio.com/static/img/3.jpg',
              productName: '手工奶皮子酸奶',
              specification: '蜜桃味',
              price: 9.00,
              quantity: 1,
              createTime: '2025-09-22 16:45:30'
            }
          ],
          // 待收货订单
          [
            {
              id: 1004,
              orderNo: '202509210001',
              status: 2,
              statusText: '待收货',
              statusClass: 'shipping',
              productImage: 'https://xxx.xjdio.com/static/img/4.jpg',
              productName: '手工奶皮子酸奶',
              specification: '芒果味',
              price: 9.00,
              quantity: 1,
              createTime: '2025-09-21 10:15:22'
            },
            {
              id: 1005,
              orderNo: '202509210002',
              status: 2,
              statusText: '待收货',
              statusClass: 'shipping',
              productImage: 'https://xxx.xjdio.com/static/img/5.jpg',
              productName: '手工奶皮子酸奶',
              specification: '红枣味',
              price: 9.00,
              quantity: 1,
              createTime: '2025-09-21 09:30:45'
            },
            {
              id: 1006,
              orderNo: '202509200001',
              status: 2,
              statusText: '待收货',
              statusClass: 'shipping',
              productImage: 'https://xxx.xjdio.com/static/img/2.jpg',
              productName: '手工奶皮子酸奶',
              specification: '黑色',
              price: 8.00,
              quantity: 1,
              createTime: '2025-09-20 14:20:33'
            }
          ],
          // 待确认订单
          [],
          // 已完成订单
          [
            {
              id: 1007,
              orderNo: '202509150001',
              status: 4,
              statusText: '已完成',
              statusClass: 'completed',
              productImage: 'https://xxx.xjdio.com/static/img/4.jpg',
              productName: '手工奶皮子酸奶',
              specification: '蓝莓味',
              price: 9.00,
              quantity: 1,
              createTime: '2025-09-15 11:05:18'
            },
            {
              id: 1008,
              orderNo: '202509100001',
              status: 4,
              statusText: '已完成',
              statusClass: 'completed',
              productImage: 'https://xxx.xjdio.com/static/img/1.jpg',
              productName: '手工奶皮子酸奶',
              specification: '苹果味',
              price: 9.90,
              quantity: 1,
              createTime: '2025-09-10 16:40:52'
            }
          ]
        ],
        currentOrders: [] // 当前显示的订单列表
    },
    // 顶部按钮点击事件（免费入会）
    join() {
        wx.showToast({
            title: '已加入会员',
            icon: 'success'
        });
    },
    navigateToaddress() {
        wx.navigateTo({
            url: '/packageA/pages/address/index',
        })
    },
    // 资产栏点击事件（跳转对应页面）
    navigateToAssets(e) {
        const type = e.currentTarget.dataset.type;
        wx.navigateTo({
            url: `/pages/asset/asset?type=${type}`
        });
    },
    navigateToassets(){
        wx.navigateTo({
          url: '/packageA/pages/wallet/index',
        })
    },

    // 功能栏点击事件（跳转对应页面）
    navigateToOrders() {
        wx.switchTab({
          url: '/pages/order/order',
        })
    },
    navigateToCoupons() {
        wx.navigateTo({
            url: '/pages/coupons/coupons'
        });
    },
    navigateToProfile() {
        wx.navigateTo({
            url: '/pages/profile/profile'
        });
    },
    navigateToAbout() {
        wx.navigateTo({
            url: '/pages/about/about'
        });
    },
    navigateToSwitch() {
        wx.navigateTo({
            url: '/pages/adminLogin/index',
        })
    },
    navigateTomanage(){
        wx.navigateTo({
          url: '/pages/management/index',
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
 // 初始化显示待付款订单
 this.setData({
    currentOrders: this.data.orders[0]
  });
    },
 // 切换订单选项卡
 switchOrderTab: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentOrderTab: index,
      currentOrders: this.data.orders[index]
    });
  },

  // 查看全部订单
  viewAllOrders: function() {
    wx.showToast({
      title: '跳转到全部订单页面',
      icon: 'none'
    });
    // 实际开发中这里应该跳转到订单列表页面
    wx.switchTab({
      url: '/pages/order/order'
    });
  },

  // 支付订单
  payOrder: function(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认支付',
      content: '您确定要支付该订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          });
          
          // 模拟支付成功后更新订单状态
          setTimeout(() => {
            this.updateOrderStatus(orderId, 1); // 更新为待发货状态
          }, 1500);
        }
      }
    });
  },

  // 更新订单状态
  updateOrderStatus: function(orderId, newStatus) {
    const orders = this.data.orders;
    let orderIndex = -1;
    let tabIndex = -1;
    
    // 查找订单
    for (let i = 0; i < orders.length; i++) {
      for (let j = 0; j < orders[i].length; j++) {
        if (orders[i][j].id === orderId) {
          orderIndex = j;
          tabIndex = i;
          break;
        }
      }
      if (orderIndex !== -1) break;
    }
    
    if (orderIndex !== -1 && tabIndex !== -1) {
      // 从原状态数组中移除
      const order = orders[tabIndex].splice(orderIndex, 1)[0];
      
      // 更新订单状态
      order.status = newStatus;
      
      // 根据新状态设置状态文本和类名
      if (newStatus === 1) {
        order.statusText = '待发货';
        order.statusClass = 'pending';
      } else if (newStatus === 2) {
        order.statusText = '待收货';
        order.statusClass = 'shipping';
      } else if (newStatus === 4) {
        order.statusText = '已完成';
        order.statusClass = 'completed';
      }
      
      // 添加到新状态数组
      orders[newStatus].unshift(order);
      
      // 更新订单数量
      const orderCounts = this.data.orderCounts;
      orderCounts[tabIndex] -= 1;
      orderCounts[newStatus] += 1;
      
      // 更新数据
      this.setData({
        orders: orders,
        orderCounts: orderCounts,
        currentOrders: orders[this.data.currentOrderTab]
      });
    }
  },

  // 立即提现
  withdraw: function() {
    wx.showModal({
      title: '提现申请',
      content: '您确定要申请提现吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '提现申请已提交',
            icon: 'success'
          });
        }
      }
    });
  },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 页面显示时更新tab状态
        console.log('我的页面显示');
        // 使用全局函数更新tab状态
        // app.setCurrentTab(3);
    },
    // 正确的getTabBar函数实现
    getTabBar: function () {
        // 避免递归调用，直接使用selectComponent
        const pages = getCurrentPages();
        if (pages.length === 0) return null;

        const currentPage = pages[pages.length - 1];
        return currentPage.selectComponent('#custom-tab-bar');
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})